package com.wenzhoujie;

import java.util.List;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.wenzhoujie.library.dialog.SDDialogConfirm;
import com.wenzhoujie.library.dialog.SDDialogCustom;
import com.wenzhoujie.library.dialog.SDDialogCustom.SDDialogCustomListener;
import com.wenzhoujie.library.title.SDTitleSimple.SDTitleSimpleListener;
import com.wenzhoujie.library.utils.SDToast;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.fragment.OrderDetailFeeFragment;
import com.wenzhoujie.fragment.OrderDetailGoodsFragment;
import com.wenzhoujie.fragment.OrderDetailGroupCouponsFragment;
import com.wenzhoujie.fragment.OrderDetailInfoFragment;
import com.wenzhoujie.fragment.OrderDetailParamsFragment;
import com.wenzhoujie.fragment.OrderDetailPaymentsFragment;
import com.wenzhoujie.fragment.OrderDetailParamsFragment.OrderDetailParamsFragmentListener;
import com.wenzhoujie.fragment.OrderDetailPaymentsFragment.OrderDetailPaymentsFragmentListener;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.DealOrderItemModel;
import com.wenzhoujie.model.DeliveryModel;
import com.wenzhoujie.model.FeeinfoModel;
import com.wenzhoujie.model.OrderDetailCoupon_listModel;
import com.wenzhoujie.model.OrderGoodsModel;
import com.wenzhoujie.model.Order_parmModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.act.BaseActModel;
import com.wenzhoujie.model.act.Calc_orderActModel;
import com.wenzhoujie.model.act.Done_orderActModel;
import com.wenzhoujie.model.act.My_order_detailActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewInject;
import com.wenzhoujie.work.AppRuntimeWorker;

public class OrderDetailActivity extends BaseActivity implements
		OnClickListener {
	/** 订单id */
	public static final String EXTRA_ORDER_ID = "extra_order_id";

	/** 取消订单成功 */
	public static final int RESULT_CODE_DELETE_ORDER_SUCCESS = 1;

	@ViewInject(id = R.id.act_order_detail_ptrsv_all)
	private PullToRefreshScrollView mPtrsvAll = null;

	@ViewInject(id = R.id.act_order_detail_ll_all)
	private LinearLayout mLlAll = null;

	@ViewInject(id = R.id.act_order_detail_ll_tip_info)
	private LinearLayout mLlTipInfo = null; // 顶部信息提示框

	@ViewInject(id = R.id.act_order_detail_tv_tip_info)
	private TextView mTvTipInfo = null;// 顶部信息提示

	@ViewInject(id = R.id.act_order_detail_ll_has_submit_order)
	private LinearLayout mLlHasSubmitOrder = null; // 提交按钮布局

	@ViewInject(id = R.id.act_order_detail_btn_submit_order)
	private Button mBtnSubmitOrder = null; // 提交按钮

	@ViewInject(id = R.id.act_order_detail_ll_has_kd_setting)
	private LinearLayout mLlHasKdSetting = null; // 快递设置布局

	@ViewInject(id = R.id.act_order_detail_btn_orders_kd)
	private Button mBtnOrdersKd = null; // 快递跟踪

	@ViewInject(id = R.id.iv_order_detail_state)
	private ImageView mImgdetail_State;

	private My_order_detailActModel mOrderDetailModel = null;

	private boolean mIsCaculateCartSuccess = false;

	private String id = null;// 订单ID

	// -------------------------fragments
	private OrderDetailFeeFragment mFragFees = null;
	private OrderDetailInfoFragment mFragInfo = null;
	private OrderDetailGoodsFragment mFragGoods = null;
	private OrderDetailPaymentsFragment mFragPayments = null;
	private OrderDetailParamsFragment mFragParams = null;
	private OrderDetailGroupCouponsFragment mFragGroupCoupons = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setmTitleType(TitleType.TITLE_SIMPLE);
		setContentView(R.layout.act_order_detail);
		IocUtil.initInjectedView(this);
		init();
	}

	private void init() {
		initIntentData();
		initTitle(false);
		registeClick();

		initPullToRefreshScrollView();
	}

	private void initPullToRefreshScrollView() {
		mPtrsvAll.setMode(Mode.PULL_FROM_START);
		mPtrsvAll.setOnRefreshListener(new OnRefreshListener2<ScrollView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
				requestOrderDetail();
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
			}

		});
		mPtrsvAll.setRefreshing();
	}

	private void initIntentData() {
		id = getIntent().getStringExtra(EXTRA_ORDER_ID);
	}

	private void initTitle(boolean canDeleteOrder) {
		mTitleSimple.setmListener(new SDTitleSimpleListener() {

			@Override
			public void onRightButtonCLick_SDTitleSimple(View v) {
				if (id != null) {
					// TODO 请求取消订单接口
					requestDeleteOrder();
				}
			}

			@Override
			public void onLeftButtonCLick_SDTitleSimple(View v) {
				finish();
			}
		});

		mTitleSimple.setTitleTop("订单详情");
		if (canDeleteOrder) {
			mTitleSimple.setRightLayoutClick(mTitleSimple);
			mTitleSimple.setRightText("取消订单");
		} else {
			mTitleSimple.setRightLayoutClick(null);
			mTitleSimple.setRightText("");
		}
	}

	/**
	 * 请求提交订单
	 */
	private void requestDoneOrder() {
		if (id != null && AppHelper.getLocalUser() != null) {
			RequestModel model = new RequestModel();
			model.put("act", "done_order");
			model.put("email", AppHelper.getLocalUser().getUser_name());
			model.put("pwd", AppHelper.getLocalUser().getUser_pwd());
			model.put("id", id);
			if (mFragParams != null) {
				DeliveryModel deliveryModel = mFragParams.getDeliveryModel();
				if (deliveryModel != null) {
					model.put("address_id", deliveryModel.getId());
					model.put("region_lv1", deliveryModel.getRegion_lv1());
					model.put("region_lv2", deliveryModel.getRegion_lv2());
					model.put("region_lv3", deliveryModel.getRegion_lv3());
					model.put("region_lv4", deliveryModel.getRegion_lv4());
					model.put("delivery_detail",
							deliveryModel.getDelivery_detail());// 配送地址
					model.put("phone", deliveryModel.getPhone());// 收件人手机
					model.put("consignee", deliveryModel.getConsignee());// 收件人
					model.put("postcode", deliveryModel.getPostcode());// 邮编
				}
				model.put("content", mFragParams.getContent());
				model.put("send_mobile", mFragParams.getMobile());
				model.put("delivery_id", mFragParams.getDelivery_id());
			}
			if (mFragPayments != null) {
				model.put("payment_id", mFragPayments.getPayment_id());
			}
			RequestCallBack<String> handler = new RequestCallBack<String>() {

				@Override
				public void onStart() {
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					Done_orderActModel actModel = JsonUtil.json2Object(
							responseInfo.result, Done_orderActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel)) {
						if (actModel.getResponse_code() == 1) {
							int hasPay = SDTypeParseUtil.getIntFromString(
									actModel.getHas_pay(), 0);
							if (hasPay == 1)// 1:允许继续支付;0:不允许(只保存订单数据)
							{
								if (!TextUtils.isEmpty(actModel.getOrder_id())) {
									// TODO 跳到支付界面
									Intent intent = new Intent(
											getApplicationContext(),
											PayActivity.class);
									intent.putExtra(PayActivity.EXTRA_ORDER_ID,
											actModel.getOrder_id());
									startActivity(intent);
									finish();
								}
							} else if (hasPay == 0) {
								AppHelper.hideLoadingDialog();
								requestCalculateOrder();
							}
						} else {
							bindTopTipInfo(actModel.getInfo());
						}
					}
				}

				@Override
				public void onFailure(HttpException error, String msg) {

				}

				@Override
				public void onFinish() {
					AppHelper.hideLoadingDialog();
				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		}

	}

	/**
	 * 请求取消订单接口
	 */
	protected void requestDeleteOrder() {
		if (AppHelper.getLocalUser() != null && id != null) {
			RequestModel model = new RequestModel();
			model.put("act", "my_order_del");
			model.put("email", AppHelper.getLocalUser().getUser_name());
			model.put("pwd", AppHelper.getLocalUser().getUser_pwd());
			model.put("id", id);
			RequestCallBack<String> handler = new RequestCallBack<String>() {

				@Override
				public void onStart() {
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					BaseActModel actModel = JsonUtil.json2Object(
							responseInfo.result, BaseActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel)) {
						if (actModel.getResponse_code() == 1) {
							setResult(RESULT_CODE_DELETE_ORDER_SUCCESS);
							finish();
						}
					}
				}

				@Override
				public void onFailure(HttpException error, String msg) {

				}

				@Override
				public void onFinish() {

				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		}
	}

	/**
	 * 请求重新计算订单价格
	 */
	public void requestCalculateOrder() {
		if (id != null && AppHelper.getLocalUser() != null) {
			RequestModel model = new RequestModel();
			model.put("act", "calc_order");
			model.put("email", AppHelper.getLocalUser().getUser_name());
			model.put("pwd", AppHelper.getLocalUser().getUser_pwd());
			model.put("id", id);
			if (mFragParams != null) {
				DeliveryModel deliveryModel = mFragParams.getDeliveryModel();
				if (deliveryModel != null) {
					model.put("region_lv1", deliveryModel.getRegion_lv1());
					model.put("region_lv2", deliveryModel.getRegion_lv2());
					model.put("region_lv3", deliveryModel.getRegion_lv3());
					model.put("region_lv4", deliveryModel.getRegion_lv4());
				}
				model.put("delivery_id", mFragParams.getDelivery_id());
			}
			if (mFragPayments != null) {
				model.put("payment_id", mFragPayments.getPayment_id());
			}
			RequestCallBack<String> handler = new RequestCallBack<String>() {

				@Override
				public void onStart() {
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					Calc_orderActModel actModel = JsonUtil.json2Object(
							responseInfo.result, Calc_orderActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel)) {
						if (actModel.getResponse_code() == 1) {
							bindFeeInfoData(actModel.getFeeinfo());
						} else {
							bindTopTipInfo(actModel.getInfo());
						}
					}
				}

				@Override
				public void onFailure(HttpException error, String msg) {

				}

				@Override
				public void onFinish() {
					AppHelper.hideLoadingDialog();
				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		}
	}

	/**
	 * 请求订单详情
	 */
	private void requestOrderDetail() {
		if (id != null && AppHelper.getLocalUser() != null) {
			RequestModel model = new RequestModel();
			model.put("act", "my_order_detail");
			model.put("email", AppHelper.getLocalUser().getUser_name());
			model.put("pwd", AppHelper.getLocalUser().getUser_pwd());
			model.put("id", id);
			RequestCallBack<String> handler = new RequestCallBack<String>() {

				@Override
				public void onStart() {
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					My_order_detailActModel actModel = JsonUtil.json2Object(
							responseInfo.result, My_order_detailActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel)) {
						if (actModel.getResponse_code() == 1) {
							mOrderDetailModel = actModel;
							initViewsState(actModel);
							toggleCaculateCartSuccess(true);

						} else {
							toggleCaculateCartSuccess(false);
						}
					} else {
						toggleCaculateCartSuccess(false);
					}
				}

				@Override
				public void onFailure(HttpException error, String msg) {

				}

				@Override
				public void onFinish() {
					AppHelper.hideLoadingDialog();
					mPtrsvAll.onRefreshComplete();
				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		}
	}

	private void toggleCaculateCartSuccess(boolean success) {
		mIsCaculateCartSuccess = success;
		if (success) {
			mLlAll.setVisibility(View.VISIBLE);
		} else {
			mLlAll.setVisibility(View.GONE);
		}
	}

	protected void initViewsState(My_order_detailActModel model) {
		if (model != null) {
			Order_parmModel order_parmModel = model.getOrder_parm();
			if (order_parmModel != null) {

				if (model.getHas_cancel() == 1) // 订单可以被取消
				{
					initTitle(true);
				}

				if (model.getHas_edit_delivery() == 1
						|| model.getHas_edit_delivery_time() == 1
						|| model.getHas_edit_ecv() == 1
						|| model.getHas_edit_invoice() == 1
						|| model.getHas_edit_message() == 1
						|| model.getHas_edit_moblie() == 1
						|| model.getHas_pay() == 1) {
					mLlHasSubmitOrder.setVisibility(View.VISIBLE); // 显示提交订单按钮
				} else {
					mLlHasSubmitOrder.setVisibility(View.GONE);
				}

				if (!TextUtils.isEmpty(model.getKd_sn())) // 显示快递跟踪
				{
					mLlHasKdSetting.setVisibility(View.VISIBLE);
				} else {
					mLlHasKdSetting.setVisibility(View.GONE);
				}

				// =================================绑定数据==========================================
				bindTopTipInfo(model.getInfo()); // 顶部提示框
				bindOrderGoodsData(model.getOrderGoods());// 添加商品
				bindParamsData(model);
				bindPaymentsData(model);
				bindOrderInfoData(model);
				bindFeeInfoData(model.getFeeinfo()); // 绑定费用信息
				bindGroupCouponsData(model.getCoupon_list());
			}
		}
	}

	/**
	 * 绑定团购券数据
	 * 
	 * @param coupon_list
	 */
	private void bindGroupCouponsData(
			List<OrderDetailCoupon_listModel> coupon_list) {
		mFragGroupCoupons = new OrderDetailGroupCouponsFragment();
		mFragGroupCoupons.setListOrderDetailCoupon_listModel(coupon_list);
		replaceFragment(mFragGroupCoupons,
				R.id.act_order_detail_fl_group_coupons);
	}

	/**
	 * 绑定配置信息fragment（手机号，留言等）
	 */
	private void bindParamsData(My_order_detailActModel model) {
		if (model != null) {
			mFragParams = new OrderDetailParamsFragment();
			mFragParams.setMy_order_detailActModel(model);
			mFragParams.setListener(new OrderDetailParamsFragmentListener() {
				@Override
				public void onCalculate() {
					requestCalculateOrder();
				}
			});
			replaceFragment(mFragParams, R.id.act_order_detail_fl_params);
		}
	}

	/**
	 * 绑定支付方式数据
	 */
	private void bindPaymentsData(My_order_detailActModel model) {
		if (model != null) {
			mFragPayments = new OrderDetailPaymentsFragment();
			if (model.getPay_money() > 0 && model.getHas_pay() == 1) // 显示支付方式列表
			{
				mFragPayments.setData(model.getOrder_parm(), true);
				mFragPayments.setSelectPaymentId(model.getPayment_id());
				mFragPayments
						.setListener(new OrderDetailPaymentsFragmentListener() {

							@Override
							public void onPaymentChange() {
								requestCalculateOrder();
							}
						});
			} else {
				mFragPayments.setData(model.getOrder_parm(), false);
			}
			replaceFragment(mFragPayments, R.id.act_order_detail_fl_payments);
		}
	}

	/**
	 * 绑定订单信息数据
	 * 
	 * @param model
	 */
	private void bindOrderInfoData(My_order_detailActModel model) {
		if (model != null) {
			mFragInfo = new OrderDetailInfoFragment();
			mFragInfo.setMy_order_detailActModel(model);
			replaceFragment(mFragInfo, R.id.act_order_detail_fl_info);
			setImageState(model);
		}
	}

	public void setImageState(My_order_detailActModel model) {
		if (model.getPay_status() == 0) {
			mImgdetail_State.setImageDrawable(getResources().getDrawable(
					R.drawable.order_0));
		} else {
			if (model.getPay_status() != 0) {
				mImgdetail_State.setImageDrawable(getResources().getDrawable(
						R.drawable.order_1));
			}
			if (model.getDelivery_status() != 0) {
				mImgdetail_State.setImageDrawable(getResources().getDrawable(
						R.drawable.order_2));
			}
			if (model.getOrder_status() != 0) {
				mImgdetail_State.setImageDrawable(getResources().getDrawable(
						R.drawable.order_3));
			}
		}
	}

	private void bindTopTipInfo(String info) {
		if (!TextUtils.isEmpty(info)) // 显示顶部提示信息
		{
			mLlTipInfo.setVisibility(View.VISIBLE);
			mTvTipInfo.setText(info);
		} else {
			mLlTipInfo.setVisibility(View.GONE);
		}
	}

	/**
	 * 绑定订单商品数据fragment
	 * 
	 * @param listGoodsModel
	 */
	private void bindOrderGoodsData(List<DealOrderItemModel> listGoodsModel) {
		mFragGoods = new OrderDetailGoodsFragment();
		mFragGoods.setListOrderGoodsModel(listGoodsModel);
		replaceFragment(mFragGoods, R.id.act_order_detail_fl_goods);
	}

	/**
	 * 绑定费用项目数据fragment
	 * 
	 * @param listFeeInfoModel
	 */
	private void bindFeeInfoData(List<FeeinfoModel> listFeeInfoModel) {
		mFragFees = new OrderDetailFeeFragment();
		mFragFees.setListFeeinfoModel(listFeeInfoModel);
		replaceFragment(mFragFees, R.id.act_order_detail_fl_fees);
	}

	private void registeClick() {
		mLlHasSubmitOrder.setOnClickListener(this);
		mBtnSubmitOrder.setOnClickListener(this);
		mLlHasKdSetting.setOnClickListener(this);
		mBtnOrdersKd.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.act_order_detail_btn_submit_order:
			clickSubmitOrder();
			break;

		case R.id.act_order_detail_btn_orders_kd:
			clickOrderKd();
			break;

		default:
			break;
		}
	}

	/**
	 * 提交订单
	 */
	private void clickSubmitOrder() {
		// TODO 提交订单
		if (App.getApplication().getmLocalUser() != null) {
			if (validateParams()) {
				if (!mFragPayments.getHasPayment()) // 没有支付方式，说明用户余额够支付,此时要弹出确认窗口确认
				{
					showConfirmOrderDialog();
				} else {
					requestDoneOrder();
				}
			}
		}
	}

	private void showConfirmOrderDialog() {
		new SDDialogConfirm().setTextContent("确定立即付款？")
				.setmListener(new SDDialogCustomListener() {

					@Override
					public void onDismiss(DialogInterface iDialog,
							SDDialogCustom dialog) {
					}

					@Override
					public void onClickConfirm(View v, SDDialogCustom dialog) {
						requestDoneOrder();
					}

					@Override
					public void onClickCancel(View v, SDDialogCustom dialog) {
					}
				}).show();
	}

	/**
	 * 快递跟踪
	 */
	private void clickOrderKd() {
		if (mOrderDetailModel != null
				&& !TextUtils.isEmpty(mOrderDetailModel.getKd_sn())
				&& !TextUtils.isEmpty(mOrderDetailModel.getKd_com())) {
			// TODO 把快递sn和快递com传到快递跟踪的activity
		}

	}

	private boolean validateParams() {
		// 1.判断配送地址
		if (mFragParams != null && mFragParams.getHasDeliveryAddress()) // 需要有配送地址
		{
			DeliveryModel deliveryModel = mFragParams.getDeliveryModel();
			if (deliveryModel == null) {
				SDToast.showToast("请先填写配送地址");
				return false;
			} else {
				if (TextUtils.isEmpty(deliveryModel.getConsignee())) // 收件人为空
				{
					SDToast.showToast("收件人不能为空");
					return false;
				}
				if (TextUtils.isEmpty(deliveryModel.getPhone())) // 手机号码为空
				{
					SDToast.showToast("手机号码不能为空");
					return false;
				}
				if (TextUtils.isEmpty(deliveryModel.getDelivery())) // 省市为空
				{
					SDToast.showToast("配送地区中所在省市不能为空");
					return false;
				}
				if (TextUtils.isEmpty(deliveryModel.getDelivery_detail())) // 详细地址为空
				{
					SDToast.showToast("详细地址不能为空");
					return false;
				}

				// TODO 判断是否有配送地区
				if (AppRuntimeWorker.getHas_region() == 1) {
					if (TextUtils.isEmpty(deliveryModel.getRegion_lv1())
							|| TextUtils.isEmpty(deliveryModel.getRegion_lv2())
							|| TextUtils.isEmpty(deliveryModel.getRegion_lv3())
							|| TextUtils.isEmpty(deliveryModel.getRegion_lv3())) {
						SDToast.showToast("配送地址中的，所在地区不能为空");
					}
				}
			}
		}

		// 2.判断配送方式
		if (mFragParams != null && mFragParams.getHasDeliveryMode()) // 需要配送方式
		{
			if (TextUtils.isEmpty(mFragParams.getDelivery_id())) {
				SDToast.showToast("请选择配送方式");
				return false;
			}
		}

		// 2.判断手机号
		if (mFragParams != null && mFragParams.getHasMobile()) // 需要有手机号
		{
			if (TextUtils.isEmpty(mFragParams.getMobile())) {
				SDToast.showToast("手机号不能为空");
				return false;
			}
		}

		// 3.判断支付方式
		if (mFragPayments.getHasPayment()) // 需要选择支付方式
		{
			if (AppHelper.isEmptyString(mFragPayments.getPayment_id())
					|| AppHelper.isEmptyString(mFragPayments.getPayment_code()))// 没有选择支付方式
			{
				SDToast.showToast("请选择支付方式");
				return false;
			}
		}

		return true;
	}

}